﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 8881;   //端口  
        static Socket serverSocket;
        static void Main(string[] args)
        {
            //服务器IP地址  
            IPAddress ip = IPAddress.Parse("127.0.0.1");
       
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址：端口  
            serverSocket.Listen(10);    //设定最多10个排队连接请求  
            Console.WriteLine("这是分支1： 启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
            //通过Clientsoket发送数据  
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
            int i = 1;
            Console.ReadLine();
        }
        private  void Test()
        {
            throw new NullReferenceException();
        }
       
        /// <summary>  
        /// 监听客户端连接  
        /// </summary>  
        private static void ListenClientConnect()
        {
            //while (true)
            //{
            //Socket clientSocket = serverSocket.Accept();
            //Thread receiveThread = new Thread(ReceiveMessage);
            //receiveThread.Start(clientSocket);
            //receiveThread.IsBackground = true;
            //Socket myClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.BeginAccept(new AsyncCallback(ClientAccepted), serverSocket);
               // myClientSocket.BeginReceive(Program.result, 0, Program.result.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), myClientSocket);
            //}
           
        }
        /// <summary>
        /// 客户端连接成功
        /// </summary>
        /// <param name="ar"></param>
        public static void ClientAccepted(IAsyncResult ar)
        {
            #region
            //设置计数器
            byte[] buffer = new byte[1024];
            var socket = ar.AsyncState as Socket;
            //这就是客户端的Socket实例，我们后续可以将其保存起来
            var client = socket.EndAccept(ar);
            //客户端IP地址和端口信息
            IPEndPoint clientipe = (IPEndPoint)client.RemoteEndPoint;

            

            //接收客户端的消息(这个和在客户端实现的方式是一样的）异步
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), client);
            //准备接受下一个客户端请求(异步)
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            #endregion
        }


        /// <summary>  
        /// 接收消息  
        /// </summary>  
        /// <param name="clientSocket"></param>  
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据  
                    int receiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                    myClientSocket.Send(result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
        static void ReceiveCallback(IAsyncResult result)
        {
            Socket ts = (Socket)result.AsyncState;
            int length = ts.EndReceive(result);
            result.AsyncWaitHandle.Close();
            Program.result = new byte[Program.result.Length];
            StringBuilder sb = new StringBuilder();
            sb.Append(Encoding.ASCII.GetString(Program.result, 0, length));
            Console.WriteLine("收到消息：{0}", Encoding.ASCII.GetString(Program.result));

            //清空数据，重新开始异步接收
            
            ts.BeginReceive(Program.result, 0, Program.result.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);
        }
    }
}
